<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/WEB-INF/jsp/taglib.jsp" %>
<html>
<head>
    <c:import url="/WEB-INF/jsp/frontend/head.jsp"/>
    <c:import url="/WEB-INF/jsp/frontend/script.jsp"/>
    <link rel="stylesheet" href="<spring:url value="/css/talk.css" />"/>
    <title>会话</title>
</head>
<body>
<div class="head">
    <c:import url="/WEB-INF/jsp/frontend/header.jsp"/>
</div>
<div class="row talk-container">
    <div class="col-md-8 talk-content">
        <input name="talk-choose" type="radio" id="talk-dialogue" class="talk-choose" checked="checked">
        <label for="talk-dialogue" class="talk-choose-label" id="talk-choose-dialogue">
            <img src="<spring:url value="/images/talk/talk_w.png" />" class="dialogue-img">
        </label>
        <input name="talk-choose" type="radio" id="talk-friends" class="talk-choose">
        <label for="talk-friends" class="talk-choose-label" id="talk-choose-friends">
            <img src="<spring:url value="/images/talk/friends_b.png" />" class="friends-img">
        </label>
        <div class="row dialogue-content">
            <div class="talk-list">
                <div class="talk-list">
                    <c:forEach items="${users}" var="user">
                        <input name="item-choose" type="radio" id="item${user.userName}" class="item-choose">
                        <label for="item${user.userName}" class="talk-item" id="item-choose-friends" onclick="changeChatWindow('${user.userId}')">
                            <img src="${user.userPhoto}" class="talk-item-img img-circle">
                            <div class="talk-item-content">
                                <div class="talk-item-user">${user.userName}</div>
                                    <%--<div class="talk-item-time">16:59</div>--%>
                                    <%--<div class="talk-item-text">对话内容对话内容对话内容对话内容对话内容</div>--%>
                            </div>
                        </label>
                        <%--<div class="talk-item" onclick="changeChatWindow('${user.userId}')">--%>
                            <%--<img src="${user.userPhoto}" class="talk-item-img img-circle">--%>
                            <%--<div class="talk-item-content">--%>
                                <%--<div class="talk-item-user">${user.userName}</div>--%>
                                    <%--&lt;%&ndash;<div class="talk-item-time">16:59</div>&ndash;%&gt;--%>
                                    <%--&lt;%&ndash;<div class="talk-item-text">对话内容对话内容对话内容对话内容对话内容</div>&ndash;%&gt;--%>
                            <%--</div>--%>
                        <%--</div>--%>
                    </c:forEach>
                </div>

            </div>
            <div class="col-md-12 talk-detail">
                <div class="talk-detail-content" id="chatContent">

                </div>

                <div class="talk-reply-content">
                    <textarea id="tx" name="talk-reply" class="talk-reply-text"></textarea>
                    <input id="send" type="submit" value="发送" name="talk-send" class="talk-reply-send">
                </div>
            </div>
        </div>
        <div class="row friends-content" style="display: none;">
            <div class="talk-list">
                <div class="talk-item">
                    <img src="<spring:url value="/images/talk/person.png" />" class="talk-item-img img-circle">
                    <div class="talk-item-content">
                        <div class="talk-item-user">用户名</div>
                        <div class="talk-item-time">16:59</div>
                        <div class="talk-item-text">对话内容对话内容对话内容对话内容对话内容</div>
                    </div>
                </div>
                <div class="talk-item">
                    <img src="<spring:url value="/images/talk/person.png" />" class="talk-item-img img-circle">
                    <div class="talk-item-content">
                        <div class="talk-item-user">用户名</div>
                        <div class="talk-item-time">16:59</div>
                        <div class="talk-item-text">对话内容对话内容对话内容对话内容对话内容</div>
                    </div>
                </div>
                <div class="talk-item">
                    <img src="<spring:url value="/images/talk/person.png" />" class="talk-item-img img-circle">
                    <div class="talk-item-content">
                        <div class="talk-item-user">用户名</div>
                        <div class="talk-item-time">16:59</div>
                        <div class="talk-item-text">对话内容对话内容对话内容对话内容对话内容</div>
                    </div>
                </div>
            </div>
            <div class="col-md-12 talk-detail"></div>
        </div>
    </div>
</div>
<c:import url="/WEB-INF/jsp/frontend/footer.jsp"/>
<script src="<spring:url value="/js/bootstrap.min.js"/>"></script>
<script src="<spring:url value="/js/sockjs.min.js"/>" type="text/javascript"></script>

<script>
    var talks = document.getElementById("chatContent");

    var dialogue = $(".dialogue-content");
    var friends = $(".friends-content");
    var currentChoose = dialogue;

    var sessionUserId = "${sessionUser.userId}";
    var currentUserId;

    var websocket;
    // whether support WebSocket
    //FIXME
    //    if ('WebSocket' in window) {
    //        websocket = new WebSocket("ws://localhost:8080/websocket");
    //    } else if ('MozWebSocket' in window) {
    //        websocket = new MozWebSocket("ws://localhost:8080/websocket");
    //    } else {
    //        websocket = new SockJS("http://localhost:8080/sockjs/websocket");
    //    }

    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://edu-chains.com/websocket");
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://edu-chains.com/websocket");
    } else {
        websocket = new SockJS("http://edu-chains.com/sockjs/websocket");
    }

    // on open
    websocket.onopen = function (event) {
        console.log("  websocket.onopen  ");
    };


    // on talk
    websocket.onmessage = function (event) {
        //FIXME
        var json = JSON.parse(event.data);

        json = eval("(" + event.data + ")");
        var html = '<div class="talk-detail-item">';
        html += '<img src="';
        html += '<spring:url value="/" />' + json.fromUserPhoto.substring(1, json.fromUserPhoto.length);
        html += '" class="talk-item-img img-circle detail-img">';
        html += '<div class="detail-content">';
        html += '<div class="detail-item-text">';
        html += json.messageText;
        html += '</div>';
        html += '<div class="detail-item-time">';
        html += json.messageTime;
        html += '</div>';
        html += '</div></div>';
        $("#chatContent").append(html);
        talks.scrollTop = talks.scrollHeight;
        console.log("  websocket.onmessage   ");
    };

    // on error
    websocket.onerror = function (event) {
        console.log("  websocket.onerror  ");
    };

    // on close
    websocket.onclose = function (event) {
        console.log("  websocket.onclose  ");
    };


    // send
    $("#send").click(function () {

        var text = $("#tx").val();

        if (text == null || text == "") {
            alert(" content can not empty!!");
            return false;
        }

        var msg = {
            messageFromId: "${sessionUser.userId}",
            messageFromName: "${sessionUser.userName}",
            messageText: text,
            //messageToId: "eb3ccf4c3dda4a4da6a5d65732780c1d"
            messageToId: currentUserId
        };

        websocket.send(JSON.stringify(msg));

        var html = '<div class="talk-detail-item talk-send">';
        html += '<img src="<spring:url value="${sessionUser.userPhoto}" />" class="talk-item-img img-circle detail-img">';
        html += '<div class="detail-content">';
        html += '<div class="detail-item-text">';
        html += text;
        html += '</div>';
        html += '<div class="detail-item-time">';
        html += GMT2Str(new Date());
        html += '</div>';
        html += '</div></div>';
        $("#chatContent").append(html);
        talks.scrollTop = talks.scrollHeight;
        $("#tx").val("");
    });

    function GMT2Str(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
        var day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
        var hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours();
        var minute = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes();
        var second = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds();
        var str = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        return str;
    }

    function changeChatWindow(messageToId) {
        currentUserId = messageToId;
        $("#chatContent").html("");
        $.ajax({
            type: "GET",
            url: "<spring:url value="/chat/getChatLog" /> ",
            data: {
                messageFromId: "${sessionUser.userId}",
                messageToId: messageToId
            },
            dataType: "json",
            success: function (data) {
                var length = data.length;
                for (var i = 0; i < length; i++) {
                    var json = data[i];
                    if (data[i].messageFromId == sessionUserId) {
                        var html = '<div class="talk-detail-item talk-send">';
                        html += '<img src="<spring:url value="${sessionUser.userPhoto}" />" class="talk-item-img img-circle detail-img">';
                        html += '<div class="detail-content">';
                        html += '<div class="detail-item-text">';
                        html += json.messageText;
                        html += '</div>';
                        html += '<div class="detail-item-time">';
                        html += GMT2Str(new Date(json.messageTime));
                        html += '</div>';
                        html += '</div></div>';
                        $("#chatContent").append(html);
                        talks.scrollTop = talks.scrollHeight;
                    }
                    else {

                        var html = '<div class="talk-detail-item">';
                        html += '<img src="';
                        html += '<spring:url value="/" />' + json.fromUserPhoto.substring(1, json.fromUserPhoto.length);
                        html += '" class="talk-item-img img-circle detail-img">';
                        html += '<div class="detail-content">';
                        html += '<div class="detail-item-text">';
                        html += json.messageText;
                        html += '</div>';
                        html += '<div class="detail-item-time">';
                        html += GMT2Str(new Date(json.messageTime));
                        html += '</div>';
                        html += '</div></div>';
                        $("#chatContent").append(html);
                        talks.scrollTop = talks.scrollHeight;
                    }
                }
            }
        });
    }

    function render() {
        $("#talk-choose-dialogue").click(function () {
            $(".dialogue-img").attr("src", "<spring:url value='/images/talk/talk_w.png' />");
            $(".friends-img").attr("src", "<spring:url value='/images/talk/friends_b.png' />");
            if (currentChoose !== dialogue) {
                currentChoose.animate({height: 'toggle'}, 200, function () {
                    dialogue.animate({height: 'toggle'}, 200);
                    currentChoose = dialogue;
                });
            }
        });

        $("#talk-choose-friends").click(function () {
            $(".dialogue-img").attr("src", "<spring:url value='/images/talk/talk_b.png' />");
            $(".friends-img").attr("src", "<spring:url value='/images/talk/friends_w.png' />");
            if (currentChoose !== friends) {
                currentChoose.animate({height: 'toggle'}, 200, function () {
                    friends.animate({height: 'toggle'}, 200);
                    currentChoose = friends;
                });
            }
        });

    }

    render();

</script>
</body>
</html>